package com.niiwoo.civet.trade.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.niiwoo.civet.trade.constant.RabbitConstant;
import com.niiwoo.civet.trade.dto.request.ProjectLifeDTO;
import com.niiwoo.civet.trade.service.local.project.ProjectLifeLocalService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.Charset;

@Slf4j
@Component
public class ProjectLifeListener {
    @Autowired
    private ProjectLifeLocalService projectLifeLocalService;

    /**
     *
     * @param message 消息
     * @param channel 通道
     */
    @RabbitListener(queues = {RabbitConstant.Queue.PROJECT_LIFE_CYCLE})
    public void onMessage(ProjectLifeDTO projectLifeDTO ,Message message, Channel channel) {
        log.info("记录标的生命周期 projectLifeLocalService 监听到消息:", projectLifeDTO.toString());
        try {
          /*  String mqString = new String(message.getBody(), Charset.forName("UTF-8"));
            JSONObject jsonObject = JSON.parseObject(mqString);*/
            projectLifeLocalService.recordProjectLife(projectLifeDTO);
        } catch (Exception e) {
            log.error("记录标的生命周期 projectLifeLocalService 异常",e);
        }finally {
            doAckAnwser(message, channel);
        }
    }

    private void doAckAnwser(Message message, Channel channel) {
        try {
            //确认消息已经接收;
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException ie) {
            log.error("basic ack occur exception, the reason is : {}", ie);
        }
    }
}
